package org.orbis.chop;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.orbis.communicate.MainService;
import org.orbis.term.Term;
import org.orbis.term.TermList;
import org.orbis.tool.Header;

public class ChopperTest extends HttpServlet{
	private static final long serialVersionUID = -2218388136074979178L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
		IOException{
		resp.setCharacterEncoding("UTF-8");
		MainService srv = MainService.getInstance();
		PrintWriter out = resp.getWriter();

		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
		out.println("<title>ORBIS search system: Parser Test</title>");
		out.println("</head>");
		out.println("<body>");
		// Title bar
		out.println(Header.getTitleBar("ORBIS Search System: Parser Test"));

		// Header
		out.println(Header.getHeader(4));

		out.println("<div>");
		out.println("Chopper: " + srv.getConf().chopper().getClass().getName());
		out.println("</div>");
		out.println("<div>");
		out.println("<form method=\"GET\" action=\"chop\">");
		out.println("<table>");
		out.println("<tbody>");
		out.println("<tr>");
		out.println("<td>Input: </td>");
		out.println("<td>");
		out.println("<textarea col=20 row=400 name=\"query\" required></textarea>");
		out.println("</td>");
		out.println("</tr>");
		out.println("</tbody>");
		out.println("</table>");
		out.println("<input type=\"submit\" value=\"CHOP\">");
		out.println("</form>");
		out.println("</div>");

		String query = req.getParameter("query");
		if(query != null){
			TermList terms = srv.getConf().chopper().chop(query);
			if(terms != null){
				out.println("<div>");
				out.println("<table>");
				out.println("<tbody>");
				int count = 1;
				out.println("<tr>");
				out.println("<th>Number</th>");
				out.println("<th>Term</th>");
				out.println("<th>Frequency</th>");
				out.println("</tr>");
				for(Term term: terms){
					out.println("<tr>");
					out.println("<th style=\"text-align: center; padding: 10px;\">");
					out.println(count++);
					out.println("</th>");
					out.println("<td>");
					out.println(term.str());
					out.println("</td>");
					out.println("<td style=\"text-align: right;\">");
					out.println(term.freq());
					out.println("</td>");
					out.println("</tr>");
				}
				out.println("</tbody>");
				out.println("</table>");
				out.println("</div>");
			}
		}

		out.println("</body>");
		out.println("</html>");
	}
}
